package com.ziyun.erp.modules.freightages.service.impl;

import com.ziyun.erp.modules.freightages.service.SdbEctoolsRegionsService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.freightages.entity.FreightAreaEntity;
import com.ziyun.erp.modules.freightages.service.FreightAreaService;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.ziyun.erp.modules.freightages.dao.FreightTemplateDao;
import com.ziyun.erp.modules.freightages.entity.FreightTemplateEntity;
import com.ziyun.erp.modules.freightages.service.FreightTemplateService;
import org.springframework.transaction.annotation.Transactional;


@Service("freightTemplateService")
public class FreightTemplateServiceImpl extends ServiceImpl<FreightTemplateDao, FreightTemplateEntity> implements FreightTemplateService {

    @Autowired
    private FreightAreaService freightAreaService;

    @Autowired
    private FreightTemplateDao freightTemplateDao;

    @Autowired
    private SdbEctoolsRegionsService sdbEctoolsRegionsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String templateName = StringUtil.getRequestParamString(params.get("templateName"));
        Integer templateId = StringUtil.getRequestParamInteger(params.get("freightTemplateId"));
        Integer sellerId = StringUtil.getRequestParamInteger(params.get("seller_id"));
        Page<FreightTemplateEntity> page = this.selectPage(
                new Query<FreightTemplateEntity>(params).getPage(),
                new EntityWrapper<FreightTemplateEntity>()
                .like(StringUtils.isNotBlank(templateName),"template_name",templateName)
                .eq(templateId != null,"template_id",templateId)
                .eq("disabled",0)
                        .eq(sellerId!= null,"seller_id",sellerId)
                .orderBy("seller_id")
                .orderBy("update_time",false)//后期加上按更新时间倒叙
        );
        return new PageUtils(page);
    }

    /**
     * 更新运费模板
     * @param freightTemplate
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFreightTemplate(FreightTemplateEntity freightTemplate) {
        //若是否默认模板被设置为true,则修改其他所有用户模板为非默认模板
        if(freightTemplate.getDefTemplate() == 1){
            List<FreightTemplateEntity> defaultFreightTemplate = getDefaultFreightTemplate(freightTemplate.getSellerId());
            for (FreightTemplateEntity freightTemplateEntity:defaultFreightTemplate) {
                freightTemplateEntity.setDefTemplate(0);
                freightTemplateDao.updateAllColumnById(freightTemplateEntity);
            }
        }
        this.updateAllColumnById(freightTemplate);
        //获取所有子模板数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("template_id",freightTemplate.getTemplateId());
        map.put("disabled",0);
        //先删除所有子模板
        List<FreightAreaEntity> oldFreightAreaEntities = freightAreaService.selectByMap(map);
        if(oldFreightAreaEntities.size() > 0){
            ArrayList<Integer> freightAreaIds = new ArrayList<>();
            for (FreightAreaEntity freightAreaEntity:oldFreightAreaEntities) {
                freightAreaIds.add(freightAreaEntity.getFreightAreaId());
            }
            freightAreaService.fagDeleteFreightAreas(freightAreaIds);
        }
        //再添加新子模板
        List<FreightAreaEntity> freightAreaList = freightTemplate.getFreightAreaList();
        if(freightAreaList.size() > 0){
            for(int i = 0;i<freightAreaList.size();i++){
                freightAreaList.get(i).setTemplateId(freightTemplate.getTemplateId());
                if(StringUtils.isNotBlank(freightAreaList.get(i).getAreaIds())){
                    if(!freightAreaList.get(i).getAreaIds().endsWith(",")){
                        freightAreaList.get(i).setAreaIds(freightAreaList.get(i).getAreaIds() + ",");
                    }
                }else{
                    throw new RRException("未指定城市异常!");
                }
            }
            freightAreaService.insertBatch(freightAreaList);
        }
        //再插入修改后的模板
    }

    /**
     * 创建新运费模板
     * @param freightTemplate
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertFreightTemplate(FreightTemplateEntity freightTemplate) {
        //若是否默认模板被设置为true,则修改其他所有用户模板为非默认模板
        if(freightTemplate.getDefTemplate() == 1){
            List<FreightTemplateEntity> defaultFreightTemplate = getDefaultFreightTemplate(freightTemplate.getSellerId());
            for (FreightTemplateEntity freightTemplateEntity:defaultFreightTemplate) {
                freightTemplateEntity.setDefTemplate(0);
                freightTemplateDao.updateAllColumnById(freightTemplateEntity);
            }
        }
        freightTemplateDao.insertFreightTemplate(freightTemplate);
        Integer templateId = freightTemplate.getTemplateId();
        List<FreightAreaEntity> freightAreaList = freightTemplate.getFreightAreaList();
        if(freightAreaList.size() > 0){
            for(int i = 0;i<freightAreaList.size();i++){
                freightAreaList.get(i).setTemplateId(templateId);
                if(StringUtils.isNotBlank(freightAreaList.get(i).getAreaIds()) && !freightAreaList.get(i).getAreaIds().endsWith(",")){
                    freightAreaList.get(i).setAreaIds(freightAreaList.get(i).getAreaIds() + ",");
                }else{
                    throw new RRException("未指定城市异常!");
                }
            }
            freightAreaService.insertBatch(freightAreaList);
        }
    }

    /**
     * 标记删除
     * @param templateIds
     */
    @Override
    public void flagDelete(Integer[] templateIds) {
        freightTemplateDao.flagDelete(templateIds);
    }

    @Override
    public R newList(Map<String, Object> params) {
        Page<FreightTemplateEntity> freightTemplatePage = new Page<>();////marketable current size total
        freightTemplatePage.setSize((Integer)params.get("size"));
        freightTemplatePage.setCurrent((Integer)params.get("current"));
        freightTemplatePage.setRecords(this.baseMapper.queryFreightTemplateList(freightTemplatePage,params));
        List<Map> allRegions = sdbEctoolsRegionsService.getAllRegions();
        return R.ok().put("page",freightTemplatePage).put("allRegions",allRegions);
    }


    /**
     * 查找当前用户默认运费模板
     */
    public List<FreightTemplateEntity> getDefaultFreightTemplate(Integer sellerId) {
        HashMap<String, Object> map = new HashMap<String, Object>();
//        map.put("supplier_id",curentUser.getUserId());
        map.put("disabled",0);
        map.put("def_template",1);
        map.put("seller_id",sellerId);
        List<FreightTemplateEntity> freightTemplateEntities = freightTemplateDao.selectByMap(map);
//        if(freightTemplateEntities.size() > 1){
//            //当前用户有2个默认模板,跑出异常
//            throw new Exception("该用户有两个默认模板!数据非法");
//        }
        return freightTemplateEntities;
    }
    /**
     *
     */
}
